<template>
  <view>
    <view>
      <scroll-view class="msg-scroll-wrap" v-if="$store.getters.getChartMapByChartUserId(chartUserId)" :style="{height: height+'px'}" :scroll-into-view="transSVId" @scrolltoupper="queryMoreChartMsgs" scroll-y>
        <view :class="isSelf(item.userId)? 'msg-right-all-wrap':'msg-left-all-wrap'"
              v-for="(item, index) in $store.getters.getChartMapByChartUserId(chartUserId).chartMsgVos" :id="'p'+index">
          <view :class="isSelf(item.userId)? 'msg-right-wrap':'msg-left-wrap'"  >
            <view class="msg-headImg-wrap">
              <image v-if="getHeadImg(item.userId)" class="msg-headImg" 
                              :src="getHeadImg(item.userId)"/>
              <span v-if="!getHeadImg(item.userId)" class="msg-headImg-defalut">
                <b>
                  {{isSelf(item.userId)?nickname?nickname.substring(0,1):'':chartName?chartName.substring(0,1):''}}
                </b>
              </span>
            </view>
            <view class="msg-detail-wrap">
              <span> {{ fromatDate(item.createTime) }} </span>
              <view :class="isSelf(item.userId)? 'msg-right-detail':'msg-left-detail'">
                {{ item.msgDetail }}
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="footer" ref="footer" id="footer">
      <view class="content-wrap">
        <textarea class="content" style="min-height: 65rpx; max-height: 180rpx;;" v-model="text" maxlength="-1" auto-height />
      </view>
      <view class="btn-wrap">
        <button
          class="btn"
          :disabled="disable"
          :class="{ disabled: disable }"
          @click="handleSend"
        >
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import {mapGetters} from 'vuex'
import {formatSimpleDate} from '../../common/utils/commonUtils'
import moment from 'moment'

export default {
  data() {
    return {
      text: "",
      height: 0,
      pageHeight: 0,
      disable: true,
      footerHeight: 0,
      keyBoardHeight: 0,
      scrollTop: 0,
      transSVId: '',
      chartUserId:'',
      chartName:'',
      headUserImgUrl:'',
	  isPopKey:true,
	  chartMap:{},
    };
  },
  watch: {
    text(newVal) {
      if (newVal.trim() != "") {
        this.disable = false;
      } else {
        this.disable = true;
      }
    },
    chartChange(newData, oldData){
      console.log('监听到数据变化'+this.chartChange)
      setTimeout(()=>{
          this.transSVId='p'+(this.$store.state.charts.chartMap[this.chartUserId].chartMsgVos.length-1)
      },300)
    }
  },
  computed: {
    ...mapGetters(['nickname', 'userId', 'headImgUrl', 'chartChange']),
	
  },

  onReady() {
    uni.getSystemInfo({
      success: (res) => {
        this.pageHeight = res.windowHeight - res.statusBarHeight
      },
    });
  },
  onLoad(chartInfo) {
    this.chartUserId = chartInfo.chartUserId;
    if(!this.$store.state.charts.chartMap
          || !this.$store.state.charts.chartMap[this.chartUserId]){
        uni.switchTab({url:'/pages/charts/index'})
        return
    }
    if(this.$store.state.charts.chartMap
          && this.$store.state.charts.chartMap[this.chartUserId]
          && this.$store.state.charts.chartMap[this.chartUserId].chartMsgVos.length<20){
	  console.log('获取消息')
      this.$store.dispatch("getChartMsg",this.chartUserId)
    }
	uni.setNavigationBarTitle({
	  title: this.$store.state.charts.chartMap[this.chartUserId].chartUserName,
	});
	this.chartName = this.$store.state.charts.chartMap[this.chartUserId].chartUserName;
	this.headUserImgUrl = this.$store.state.charts.chartMap[this.chartUserId].headUserImgUrl;
    this.initListener();
    setTimeout(()=>{
        this.transSVId='p'+(this.$store.state.charts.chartMap[this.chartUserId].chartMsgVos.length-1)
    },300)
  },
  onUnload() {
    this.destoryListener();
    // 更新该会话所有未读聊天信息都为已读
    this.$store.dispatch('updateMsgIsRead',this.chartUserId)
  },
  mounted() {
    this.$nextTick(() => {
		console.log('dom变化')
      // #ifdef H5
      this.footerHeight = this.$refs.footer.$el.offsetHeight;
      this.height = this.pageHeight - this.footerHeight;
      // #endif
    });
	// #ifdef MP-WEIXIN
	uni
	  .createSelectorQuery()
	  .select("#footer")
	  .boundingClientRect((data) => {
		  console.log('输入框的高度：'+data.height)
		  this.height = this.pageHeight-10;
		  }).exec();
	// #endif
  },
  methods: {
    fromatDate(date) {
        return formatSimpleDate(date)
    },
    getHeadImg(userId){
      return this.isSelf(userId)? this.headImgUrl:this.headUserImgUrl
    },
    isSelf(userId){
      return parseInt(userId)=== parseInt(this.userId)
    },
    initListener() {
      uni.onKeyboardHeightChange((res) => {
		  console.log('键盘高度变化'+res)
  //       let keyBoardHeight = res.height;
  //       if (this.keyBoardHeight == 0 && keyBoardHeight > 0) {
  //         this.keyBoardHeight = keyBoardHeight;
  //       }
  //       if (keyBoardHeight > 0) {
		//   console.log('变大')
		//   if(this.isPopKey){
		// 	this.isPopKey=false
		// 	this.height = this.height - this.keyBoardHeight;  
		//   }
		// } else {
		//   console.log('变小')
  //         this.height = this.height + this.keyBoardHeight;
		//   this.isPopKey=true
  //       }
		// console.log(this.height)
      });
    },
    destoryListener() {
      uni.offKeyboardHeightChange((res) => {
        console.log("offKeyboardHeightChange...");
      });
    },
    handleLeftClick() {
    
    },
    handleSend() {
      let chartInfo={
        chartUserId:this.chartUserId,
        chartUserName:this.chartName,
        headUserImgUrl:this.headUserImgUrl,
        lastMsgTime:moment().format("yyyy-MM-DD HH:mm:ss"),
        msgData:{
          event:'SEND_MSG_TO_USER',
          userId:this.userId,
          userName:this.nickname,
          isNewChart:this.$store.state.charts.chartMap[this.chartUserId].isNewChart?true:false,
          userHeadImg:this.headImgUrl,
          receiveUserId:this.chartUserId,
          msgType:'STR',
          msgDetail:this.text,
          isRead:1,
          createTime:moment().format("yyyy-MM-DD HH:mm:ss"),
        }
      }
      this.text=''
      this.$store.dispatch("sendMsg",chartInfo)
      this.$websocket.send(JSON.stringify(chartInfo.msgData))
      this.$store.commit('SET_NOTNEWCHART',this.chartUserId)
      setTimeout(()=>{
        this.transSVId='p'+(this.$store.state.charts.chartMap[this.chartUserId].chartMsgVos.length-1)
      },300)
    },
    queryMoreChartMsgs(){
    if(this.$store.state.charts.chartMap
          && this.$store.state.charts.chartMap[this.chartUserId]){
      this.$store.dispatch("getChartMsg",this.chartUserId)
    }
    }
  },
};
</script>

<style lang="scss">
$head_img_size: 100rpx;
page {
  background-color: #f3f3f3;
}
.footer {
  width: 100%;
  background-color: #e9edf4;
  display: flex;
  position: fixed;
  bottom: 0;
}

.footer .content-wrap {
  width: 78%;
  margin-left: 2%;
}

.footer .content {
  width: 100%;
  box-sizing: border-box;
  margin: 14rpx 0;
  background-color: #ffffff;
  border-radius: 30rpx;
  padding: 16rpx;
  caret-color: #01b4fe;
}

.footer .btn-wrap {
  width: 18%;
  margin-right: 2%;
}

.footer .btn {
  width: 15%;
  height: 65rpx;
  font-size: 26rpx;
  margin-left: 2%;
  background-color: #01b4fe;
  color: #ffffff;
  position: fixed;
  bottom: 14rpx;
  border: 0;
  outline: none;
}

.footer .btn-wrap .disabled {
  background-color: #aae8f5;
}
/* #ifdef H5 */
::v-deep .uni-textarea-wrapper {
  max-height: 180rpx;
}
/* #endif */

.msg-scroll-wrap {
  display: flex;
  flex-direction: column;
}
.msg-right-all-wrap {
  display: flex;
  flex-direction: row-reverse;
  margin-bottom: 30rpx;
  margin-right: 10px;
}
.msg-left-all-wrap {
  display: flex;
  flex-direction: row;
  margin-bottom: 30rpx;
  margin-left: 10px;
}
.msg-right-wrap {
  display: flex;
  flex-direction: row-reverse;
  width: calc(100% - 2*$head_img_size);
}
.msg-left-wrap {
  display: flex;
  flex-direction: row;
  width: calc(100% - 2*$head_img_size);
}
.msg-headImg-wrap {
  display: flex;
  flex-direction: column;
}
.msg-headImg {
  height: $head_img_size;
  width: $head_img_size;
  border-radius: 15rpx;

}
.msg-headImg-defalut {
  height: $head_img_size;
  width: $head_img_size;
  background-color: #37a8a6;
  border-radius: 15rpx;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content:center;
  font-size: 35rpx;
  color: #ffffff;
}
.msg-detail-wrap {
  width: calc(100% - $head_img_size);
  margin-left: 20rpx;
  margin-right: 20rpx;
}

.msg-left-detail {
  word-break:break-all;
  margin-top: 10rpx;
  background-color: #ffffff;
  padding: 15rpx;
  border-radius: 15rpx;
}
.msg-right-detail {
  word-break:break-all;
  margin-top: 10rpx;
  background-color: #aaf5bd;
  padding: 15rpx;
  border-radius: 15rpx;
}
</style>